<?php
declare(strict_types=1);

namespace App\Controller;

use App\Lib\Pagination;
use App\Model\Product;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\View\RenderInterface;
use function Hyperf\ViewEngine\view;
use Hyperf\HttpServer\Contract\RequestInterface;

#[AutoController]
class ProductController extends AbstractController
{
    private $params = [
        'filter_name' => '',
        'filter_status' => '',
        'filter_date_start' => '',
        'filter_date_end' => '',
        'filter_brand' => '',
        'sort' => 'date_added',
        'sort_name' => 'product_id',
        'sort_brand' => '',
        'sort_quantity' => '',
        'sort_sales' => '',
        'sort_orders' => '',
        'sort_status' => '',
        'sort_date'=>'',
        'order' => 'desc',
        'page' => '',
        'product_id' => '',
        'statuses' => ['*' => '全部状态', '1' => '已下架', '2' => '正在销售', '3' => '停止销售'],
    ];

    public function index(RequestInterface $request)
    {
        $data = $request->all();
        $data = array_merge($this->params, $data);

        $query = Product::query();
        if ($data['filter_name'])
            $query = $query->where('product_name', 'like', '%' . $data['filter_name'] . '%');
        if($data['sort']) {
            $query = $query->orderBy($data['sort'], $data['order']);
        } else {
            $query = $query->orderBy('date_added', 'desc');
        }

        $paginate = $query->paginate();
        $data['products'] = $paginate->items();
        foreach ($data['products'] as &$product) {
            $options = $product->options;
            if(!empty($options)) {
                $product['image'] = $options[0]['option_image'];
            }
            $product['status'] = $data['statuses'][$product['status']]??'';
        }
        $data['results'] = $paginate->total();
        return view('products/product_list', $data);
    }
}